<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">废物实时提交记录</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">

                    <a-col :md="8" :sm="24">
                        <a-form-item label="提交时间">
                            <a-range-picker
                                :show-time="{ format: 'HH:mm' }"
                                :placeholder="['开始时间', '结束时间']"
                                v-model="rangeTime"
                                format="YYYY-MM-DD HH:mm"
                                @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <a-col :md="10" :sm="24" v-if="(customerList.length <= 0) && (showSelectArea)">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea"></select-area>
                        </a-form-item>
                    </a-col>
                    <template v-if="toggleSearchStatus">
                        <a-col :md="24" :sm="24" v-if="customerList.length">
                            <a-row :gutter="24">
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="机构选择">
                                        <a-select placeholder="选择机构" v-model="queryParam.customerNumber">
                                            <a-select-option
                                                v-for="(item,index)  in customerList" :key="index"
                                                :value="item['customerNumber']">
                                                {{ item['customerName'] }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="废物编码">
                                        <a-input v-model="queryParam.recycleBagCode" placeholder="废物编码"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="部门名称">
                                        <a-input v-model="queryParam.customerDepartmentName" placeholder="部门名称"/>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-col>

                        <a-col :md="24" :sm="24" v-if="customerList.length <= 0">
                            <a-row :gutter="24">
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="废物编码">
                                        <a-input v-model="queryParam.recycleBagCode" placeholder="废物编码"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="机构名称">
                                        <a-input v-model="queryParam.customerName" placeholder="机构名称"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="部门名称">
                                        <a-input v-model="queryParam.customerDepartmentName" placeholder="部门名称"/>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-col>

                        <a-col :md="24" :sm="24" v-if="customerList.length <= 0">
                            <a-row :gutter="24">
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="产生单位">
                                        <select-customer-list ref="selectCustomerRef" @change="changeCustomer"></select-customer-list>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24" v-has="'query:company:select:auth'">
                                    <a-form-item label="处置单位">
                                        <select-company-list :companysId="queryParam.companysId" @change="changeCompany"></select-company-list>
                                    </a-form-item>
                                </a-col>
                                <a-col :md="6" :sm="24">
                                    <a-form-item label="异常情况">
                                        <a-select placeholder="废物异常情况" v-model="queryParam.isSynchronization">
                                            <a-select-option value="">全部</a-select-option>
                                            <a-select-option value="0">成功</a-select-option>
                                            <a-select-option value="1">失败</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-col>
                    </template>

                    <a-col :md="6" :sm="8">
                        <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                          <a @click="handleToggleSearch" style="margin-left: 8px">
                            {{ toggleSearchStatus ? '收起条件' : '展开条件' }}
                            <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                          </a>
                        </span>
                    </a-col>

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button v-if="customerList.length <= 0" type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
            </div>
        </div>

        <div>
            <CheckboxWasteType ref="CheckboxWasteType" :companysId="queryParam.companysId"  @change="changeWasteType"></CheckboxWasteType>
        </div>

        <!-- table区域-begin -->
        <div>
            <a-table
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="loading"
                class="j-table-force-nowrap"
                @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="getImgView(text)" height="25px" alt=""
                         style="width: auto;height: 50px;"/>
                </template>
                <template slot="fileSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                    <a-button
                        v-else
                        :ghost="true"
                        type="primary"
                        icon="download"
                        size="small"
                        @click="uploadFile(text)"
                    >下载
                    </a-button>
                </template>

                <!--v-has="'delete:customer_waste'"-->
                <span slot="action" slot-scope="text, record">
                  <a  @click="showModal(record)">删除</a>
                    <!--                  <a-divider type="vertical"/>-->
                </span>
            </a-table>
        </div>

        <a-modal v-if="editData"
                 v-model="visible"
                 :title="'删除【'+editData.customerName+'】机构废物信息'"
        >
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :sm="24">
                        <a-form-item label="机构名称">
                            <div>{{editData.customerName || '--'}}</div>
                        </a-form-item>
                    </a-col>
                    <a-col :sm="24">
                        <a-form-item label="废物编码">
                            <div>{{editData.recycleBagCode || '--'}}</div>
                        </a-form-item>
                    </a-col>
                    <a-col :sm="24">
                        <a-form-item label="废物名称">
                            <div>{{editData.wasteName || '--'}}</div>
                        </a-form-item>
                    </a-col>
                    <a-col :sm="24">
                        <a-form-item label="废物量">
                            <div>{{editData.wasteOriginalValue ||0}}{{editData.priceUnit || ''}}</div>
                        </a-form-item>
                    </a-col>
                    <a-col :sm="24">
                        <a-form-item label="删除原因"></a-form-item>
                        <a-textarea style="width: 100%;" v-model="deleteRemark" placeholder="删除原因" :rows="4"/>
                    </a-col>
                </a-row>
            </a-form>

            <template slot="footer">
                <a-button key="back" @click="handleCancel">
                    关闭
                </a-button>
                <a-button type="danger" :loading="loading" @click="handleOk()">
                    删除
                </a-button>
            </template>
        </a-modal>


        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">
                    废物实时提交记录
                </h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                    size="small"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                </a-table>
            </div>
        </div>

    </a-card>

</template>

<script>
/**
 * create by Jane
 * 二维码回溯
 */
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SelectArea from '@/components/Jane/SelectArea'
import SelectCompanyList from '@/components/Jane/SelectCompanyList'
import SelectCustomerList from '@/components/Jane/SelectCustomerList'
import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

import { downloadFile, putAction } from '../../../api/manage'
import * as user from '../../../api/user' // 模糊下拉查询
import { GET_USER_AUTH } from '@/utils/util'
import waste from '@api/waste'
import * as customer from '@api/customer'

export default {
    mixins: [JeecgListMixin, mixinDevice],
    components: {
        SelectArea,
        SelectCompanyList,
        SelectCustomerList,
        CheckboxWasteType,
    },
    data() {
        return {
            description: '医废收运记录',
            rangeTime: [],
            queryParam: {
                customerNumber: null,
                customerDepartmentId: null,
                creatTimeBegin: null,
                creatTimeEnd: null
            },
            // 表头
            columns: [],
            url: {
                list: null,   // 小彭接口 3.0 : 查询数据列表
                exportXlsUrlOkForImages: '#'
            },
            dictOptions: {},
            customerList: [],
            editData: null,
            visible: false,
            deleteRemark: '',
            loading: false ,
            AUTH:{
                DELETE_CUSTOMER_WASTE: 'delete:customer_waste', // 操作
            },
            wasteTypeList: [], // 废物类型列表 (原始数据)
            wasteId: []  // 选择的废物
        }
    },
    // created() {
    //     this.changeWasteType()
    // },


    computed: {
        showSelectArea: function() {
            let state = true
            let userInfo = this.$store.getters.userInfo
            if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                state = false
            }
            return state
        }
    },

    methods: {
        // 配置默认信息
        async initDictConfig(){
            for (let i in this.queryParam) {
                this.queryParam[i] = ''
            }
            let date = new Date()
            let time1 = new Date(date.setHours(0, 0, 0, 0)).Format('yyyy-MM-dd hh:mm')
            let time2 = new Date(date.setHours(0, 0, 0, 0) + (1000 * 60 * 60 * 24 - 1)).Format('yyyy-MM-dd hh:mm')
            this.queryParam.creatTimeBegin = time1;
            this.queryParam.creatTimeEnd = time2;
            this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd];
            let orgList = await user.getAllCustomerByUserId()
            if (orgList) {
                 this.customerList = orgList || []
                 if (orgList[0]) {
                     this.queryParam.customerNumber = orgList[0].customerNumber
                 }
            }
            this.queryParam['companysId'] = null
            // 获取到用户登陆的信息
            let userInfo = this.$store.getters.userInfo;
            if (userInfo.companysId) {
                this.changeCompany(userInfo.companysId)
            }
            // if(userInfo.customerNumber){
            //     this.queryParam.customerNumber = userInfo.customerNumber
            // }
            if(userInfo.cityCode){
                this.queryParam.cityCode = userInfo.cityCode;
            }
            if(userInfo.areaCode){
                this.queryParam.areaCode = userInfo.areaCode;
            }


            // 如果
            if(!(userInfo.companysId || this.queryParam.customerNumber)){
                let userInfo = this.$store.getters.userInfo
                if (userInfo.cityCode) {
                    this.queryParam.cityCode = userInfo.cityCode
                }
                if (userInfo.areaCode) {
                    this.queryParam.areaCode = userInfo.areaCode
                }
            }
            let ref = this.$refs.selectAreaRef;
            if(ref && ref.clearSelectArea != undefined){
                ref.clearSelectArea();
            }

            let refCus = this.$refs.selectCustomerRef;
            if(refCus && refCus.clearSelectCustomer != undefined){
                refCus.clearSelectCustomer();
            }
            this.setColumns()
        },

        // 废物类型选择改变
        changeWasteType(info,wasteList) {
            this.wasteId = info.ids;
            this.queryParam.wasteId = info.ids.join(',');
            this.wasteTypeList = wasteList;
            this.url.list = '/hc/hcRecycleBagcode/queryListByStatus';
            this.setColumns();
            // this.searchQuery()
        },

        async changeCustomer(value, option) {
            this.queryParam.customerNumber = value
            this.searchQuery()
        },

        async changeCompany(value, option) {
            this.queryParam.companysId = value
            // 以下代码是解决在wasteId还没赋值前会在JeecgListMixin提前发送一次请求的bug
            let params = {}
            if(this.queryParam.companysId){
                params['companysId'] = this.queryParam.companysId;
            }
            let data = await waste.getWasteTypeListByCompanyId(params);
            let list = []
            data[0].children.forEach((val,key)=>{
                list.push(val.id)
            })
            this.wasteId = list
            this.searchQuery()
        },

        // 重置筛选表单
        resetForm : function(){
            // this.queryParam.cityCode = ''
            // this.queryParam.areaCode = ''
            // this.queryParam.customerNumber = ''
            // this.queryParam.companysId = ''
            // this.queryParam.recycleBagCode = ''
            // this.queryParam.customerName = ''
            // this.queryParam.customerDepartmentName = ''
            // this.queryParam.isSynchronization = ''
            this.initDictConfig();
            this.searchQuery();
        },


        async changeArea({ area, city }) {
            if (city) {
                this.queryParam.cityCode = city
            }
            if (area) {
                this.queryParam.areaCode = area
            }
        },


        handleDateChange(value, dateString) {
            this.rangeTime = dateString
            if (dateString[0]) {
                this.queryParam.creatTimeBegin = dateString[0]
            }
            if (dateString[1]) {
                this.queryParam.creatTimeEnd = dateString[1]
            }
        },

        searchQuery: function() {
            this.selectedRowKeys = []
            this.selectionRows = []
            this.queryParam.wasteId = this.wasteId.join(',')
            this.loadData(1)
        },

        handleMwExportXlsForImages() {
            let param = { ...this.queryParam }
            if (this.selectedRowKeys && this.selectedRowKeys.length != 1) {
                this.$message.warning('请仅选择一家机构导出！')
                return
            }

            param.customerName = this.selectionRows[0].customerName

            let name = `${param.customerName}-${new Date().FormatDate()}.xls`
            downloadFile(this.url.exportXlsUrlOkForImages, name, param)

        },

        // 删除废物信息
        showModal(row) {
            this.visible = true
            this.editData = row
        },
        handleCancel(e) {
            this.visible = false
            this.editData = null
            this.deleteRemark = ''
        },
        async handleOk() {
            if (this.deleteRemark == '') {
                this.$message.warn('请填写【审核未通过】的原因！')
                return
            }
            let params = {
                id: this.editData.id,
                delFlag: 1,
                remark: this.deleteRemark || ''
            }
            this.loading = true
            let res = await putAction('/hc/hcRecycleBagcode/edit', params)
            if (res && res.success) {
                this.visible = false
                this.loading = false
                this.deleteRemark = ''
                this.$message.success(res.message || '提交成功！')
            } else {
                this.$message.warn(res.message || '提交失败！')
            }
            this.loadData()
        },
        // 设置列
        setColumns() {
            let col = [
                {
                    title: '序号',
                    dataIndex: '',
                    key: 'rowIndex',
                    width: 60,
                    align: 'center',
                    customRender: function(t, r, index) {
                        return parseInt(index) + 1
                    }
                },
                {
                    title: '废物编码',
                    align: 'center',
                    dataIndex: 'recycleBagCode',
                    customRender: function(text) {
                        return text || ' '
                    }
                },
                {
                    title: '机构名称',
                    align: 'center',
                    dataIndex: 'customerName'
                },
                {
                    title: '所属部门',
                    align: 'center',
                    dataIndex: 'customerDepartmentName'
                },
                {
                    title: '废物名称',
                    align: 'center',
                    dataIndex: 'wasteName',
                    scopedSlots: { customRender: 'htmlSlot' },
                    customRender: function(value, row, index) {
                        let sty = 'font-weight:600;'
                        if (row.color) {
                            // sty = `font-weight:600;color:${row.color}`;
                        }
                        const obj = {
                            children: < span
                                style = { sty } > { value } < /span>,
                            attrs: {
                                }
                                }
                            return obj
                        }
                    },
                                {
                                    title: '废物量',
                                    align: 'center',
                                    dataIndex: 'wasteOriginalValue',
                                    scopedSlots: { customRender: 'htmlSlot' },
                                    customRender: function(value, row, index) {
                                    const obj = {
                                    children: < span
                                    style = 'font-weight:600;' > { value }
                                    {
                                        row.priceUnit || ''
                                    }
                                    <
                                    /span>,
                                    attrs: {
                                }
                                    }
                                    return obj
                                    }
                                    },
                                    {
                                        title: '提交人',
                                        align: 'center',
                                        dataIndex: 'submitUserName'
                                    },
                                    {
                                        title: '提交时间',
                                        align: 'center',
                                        dataIndex: 'createTime'
                                    }
                                    ]
                                    if (this.customerList.length <= 0) {
                                    // col.push({
                                    //     title: '部门/科室签字',
                                    //     align: 'center',
                                    //     dataIndex: 'customerDepartmentUrl',
                                    //     scopedSlots: { customRender: 'imgSlot' }
                                    // })
                                    col.push({
                                    title: '备注',
                                    align: 'center',
                                    dataIndex: 'remark'
                                    })
                                    if(GET_USER_AUTH(this.AUTH.DELETE_CUSTOMER_WASTE)){
                                    col.push({
                                    title: '操作',
                                    dataIndex: 'action',
                                    scopedSlots: { customRender: 'action' }
                                    })
                                    }
                                    }
                                    this.columns = col

                                    },
                                    }
                                    }
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>